package com.hz.blogservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.hz.apiservice.client.StudentApi;
import com.hz.apiservice.model.dto.StudentDTO;
import com.hz.apiservice.model.enums.ApiResponseCodeEnum;
import com.hz.apiservice.model.request.ApiResponse;
import com.hz.blogservice.mapper.BlogMapper;
import com.hz.blogservice.model.entity.BlogEntity;
import com.hz.blogservice.service.BlogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {
    @Resource
    BlogMapper blogMapper;
    @Resource
    StudentApi studentApi;

    @Override
    public int addBlog(String title, String content, Integer userId, boolean isAnonymous) {
        BlogEntity blogEntity = new BlogEntity();
        blogEntity.setTitle(title);
        blogEntity.setContent(content);
        blogEntity.setPublish_time(System.currentTimeMillis());
        blogEntity.setAuthor_id(userId);
        ApiResponse res = JSON.parseObject(studentApi.studentInfo(userId), ApiResponse.class);
        if (!res.getCode().equals(ApiResponseCodeEnum.SUCCESS.getCode())) {
            return 0;
        }

        StudentDTO studentDTO = JSON.parseObject(JSON.toJSONString(res.getData()), StudentDTO.class);
        blogEntity.setAuthor_username(studentDTO.getUsername());
        blogEntity.setAuthor_realname(studentDTO.getRealname());
        if (isAnonymous) {
            blogEntity.setIs_anonymous(1);
            blogEntity.setAnonymous_name(" 不愿透露姓名的:" + blogEntity.getAuthor_username());
        } else {
            blogEntity.setIs_anonymous(0);
        }
        return blogMapper.addBlog(blogEntity);

    }

    @Override
    public BlogEntity viewBlog(Integer id) {
        return blogMapper.selectBlog(id);
    }

    @Override
    public int delBlog(Integer id) {
        return blogMapper.delById(id);
    }

    @Override
    public int editBlog(Integer id, String title, String content) {
        return blogMapper.editBlog(id,title,content);
    }

    @Override
    public List<BlogEntity> allBlogs(){
        return blogMapper.allBlogs();
    }

    @Override
    public List<BlogEntity> myBlogs(Integer userId) {
        return blogMapper.myBlogs(userId);
    }


}
